package sm.hibernate.sql;

import org.hibernate.util.StringHelper;

public class SMDelete {

	private String tableName;
	private String[] primaryKeyColumnNames;
	private String[] indexColumnNames;
	private String versionColumnName;
	private String where;

	private String comment;

	public SMDelete setComment(String comment) {
		this.comment = comment;
		return this;
	}

	public SMDelete setTableName(String tableName) {
		this.tableName = tableName;
		return this;
	}

	public SMDelete setIndexColumnNames(String[] indexColumnNames) {
		this.indexColumnNames = indexColumnNames;
		return this;
	}

	/**
	 * handle null primary key column
	 */
	public String toStatementString() {
		StringBuilder builder = new StringBuilder(tableName.length() + 10);
		if (comment != null) {
			builder.append("/* ").append(comment).append(" */ ");
		}
		builder.append("delete from ").append(tableName);
		if (where != null || primaryKeyColumnNames != null
				|| versionColumnName != null) {
			builder.append(" where ");
		}
		boolean conditionsAppended = false;
		if (primaryKeyColumnNames != null) {
			int primaryKeyCount = primaryKeyColumnNames.length;
			for (int i = 0; i < primaryKeyCount; i++) {
				String primaryKeyColumnName = primaryKeyColumnNames[i];
				builder.append("((").append(primaryKeyColumnName)
						.append("=?) or (? is null and ")
						.append(primaryKeyColumnName).append(" is null))");
				if (i < primaryKeyCount - 1) {
					builder.append(" and ");
				}
			}

			if (indexColumnNames != null && indexColumnNames.length > 0) {
				builder.append(" and ");
				builder.append(StringHelper.join("=? and ", indexColumnNames))
						.append("=?");
			}

			conditionsAppended = true;
		}
		if (where != null) {
			if (conditionsAppended) {
				builder.append(" and ");
			}
			builder.append(where);
			conditionsAppended = true;
		}
		if (versionColumnName != null) {
			if (conditionsAppended) {
				builder.append(" and ");
			}
			builder.append(versionColumnName).append("=?");
		}
		return builder.toString();
	}

	public SMDelete setWhere(String where) {
		this.where = where;
		return this;
	}

	public SMDelete addWhereFragment(String fragment) {
		if (where == null) {
			where = fragment;
		} else {
			where += (" and " + fragment);
		}
		return this;
	}

	public SMDelete setPrimaryKeyColumnNames(String[] primaryKeyColumnNames) {
		this.primaryKeyColumnNames = primaryKeyColumnNames;
		return this;
	}

	public SMDelete setVersionColumnName(String versionColumnName) {
		this.versionColumnName = versionColumnName;
		return this;
	}

}
